package findtextinfile;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/**
Problema:

Implement search in filesystem:

cmd> java FileSearch "text in file" c:\roottestdirectory\

Searched for "text in file" in "c:\roottestdirectory\", found:
c:\roottestdirectory\test1.txt (lines 10, 12)
c:\roottestdirectory\subdir\test1.txt (line 1)

Rezolvare:

 */
public class FindTextTest {
	BufferedReader br = null;
	static boolean hasResult = true;

	public void findFile(String name, File file) throws IOException {
		File[] list = file.listFiles();

		if (list != null)

			for (File fil : list) {
				if (fil.isDirectory()) {
					findFile(name, fil);
				} else {

					searchInFile(name, fil);

				}

			}

	}

	private void searchInFile(String name, File fil) throws IOException {

		br = new BufferedReader(new FileReader(fil));
		String line;
		int row = 0;
		String fileName = null;
		ArrayList<Integer> rows = new ArrayList<Integer>();

		while ((line = br.readLine()) != null) {

			row += 1;

			if (line.contains(name)) {
				// System.out.println("line " + row);
				fileName = fil.getAbsolutePath();
				rows.add(row);
				hasResult = false;
				

			}

		}
		if (fileName != null) {

			System.out.println(fileName + "      ( line " + rows.toString()	+ " )");
		}

		br.close();

	}

	public static void main(String[] args) throws IOException {
		FindTextTest ff = new FindTextTest();
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter the text to be searched.. ");
		String name = scan.next();
		System.out.println("Enter the directory where to search ");
		String directory = scan.next();
		
		System.out.println("Searched for "+ name+" in "+directory+", found:");
		ff.findFile(name, new File(directory));
		if (hasResult) {
			System.out.println("Sorry");
scan.close();
		}
		
	}
}
